﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RoccaStore.Data;

namespace RoccaStore.Services
{
    public class AddressBookService : ServiceBase<IAddressBookRepository>, IAddressBookService
    {
        private readonly IAccountService _accountService;

        public AddressBookService(
            IAccountService accountService)
        {
            _accountService = accountService;
        }

        public List<Contact> GetByAccountID(int accountId)
        {
            return Repository.GetByAccountID(accountId);
        }

        public Contact GetByID(int id)
        {
            return Repository.GetByID(id);
        }

        public int Save(Contact addressBook)
        {
            return Repository.Save(addressBook);
        }

        public Contact Create(string email, int? accountId)
        {
            Contact addressBook = GetByEmail(email, accountId);

            if (addressBook == null)
            {
                addressBook = new Contact()
                {
                    AccountID = accountId ?? _accountService.Current.ID,
                    Email = email,
                    Name = string.Empty
                };

                Save(addressBook);
            };

            return addressBook;
        }

        public Contact GetByEmail(string email, int? accountId)
        {
            if (_accountService.Current != null)
            {
                int id = accountId ?? _accountService.Current.ID;
                return Repository.GetByEmail(email, id);
            }

            return null;
        }

        public List<Contact> GetBySearchTerm(string searchTerm, int? accountId)
        {
            int id = accountId ?? _accountService.Current.ID;
            return Repository.GetBySearchTerm(searchTerm, id);
        }
    }
}
